package com.study.animationstudy.widget

import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.animation.TypeEvaluator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.animation.LinearInterpolator
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.study.animationstudy.util.MD5Util
import com.study.animationstudy.util.MeasureUtil
import com.study.animationstudy.util.Utils
import java.util.*

/**
 *
 * @Author： LJH
 * @Time： 2022/12/17
 * @description：
 */
class BarrageView(context: Context,attrs:AttributeSet?):LinearLayout(context, attrs) {

    constructor(context: Context):this(context,null)

    companion object{
        const val TAG = "BarrageView"
        class MarginEvaluator : TypeEvaluator<Int> {
            override fun evaluate(fraction: Float, startValue: Int, endValue: Int): Int {
                return (startValue * (1 - fraction) + endValue * fraction).toInt()
            }
        }
    }
    // 弹幕行数
    private var mRowCount = 5
    // 文字大小
    private var mTextSize = 15
    // 每行的相对布局列表
    private val mLayoutList = ArrayList<RelativeLayout>()
    // 视图宽度
    private var mWidth = 0
    // 最近两次的弹幕位置
    private var mLastPos1 = -1
    private var mLastPos2 = -1
    private val COLOR_ARRAY = arrayOf(
        Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW,
        Color.CYAN, Color.MAGENTA, Color.LTGRAY, Color.GRAY,
        Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW,
        Color.CYAN, Color.MAGENTA, Color.LTGRAY, Color.GRAY)

    init {
        orientation = LinearLayout.VERTICAL
        setBackgroundColor(Color.TRANSPARENT)
        for (i in 0 until  mRowCount){
            val layout = RelativeLayout(context)
            val params = RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,Utils.dip2px(context,40f))
            layout.layoutParams = params
            layout.setBackgroundColor(Color.TRANSPARENT)
            mLayoutList.add(layout)
            // 添加至当前视图
            addView(layout)
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        // 获取视图的实际宽度
        mWidth = measuredWidth
    }

    /**
     * 获取本次弹幕的位置。不跟最近两次在同一行，避免挨得太近
     * @return Int
     */
    private fun getPos():Int{
        var pos = 0
        do {
            pos = Random().nextInt(mRowCount)
        }while (pos == mLastPos1 || pos == mLastPos2)
        mLastPos2 = mLastPos1
        mLastPos1 = pos
        return pos
    }

    /**
     * 给弹幕视图添加评论
     */
    fun addComment(comment:String){
        // 获取随机位置的相对布局
        val layout = mLayoutList[getPos()]
        // 获取评论文字的文本视图
        val tv = getCommentView(comment)
        val textWidth:Float = MeasureUtil.getTextWidth(comment,Utils.dip2px(context,
            mTextSize.toFloat()
        ).toFloat())
        layout.addView(tv)
        // 根据估值器和起止位置创建一个属性动画
        val anim = ValueAnimator.ofObject(MarginEvaluator(),-textWidth,mWidth)
        // 添加属性动画的刷新监听器
        anim.addUpdateListener {
            //获取动画的当前值
            val margin = it.animatedValue
            val tvParams = tv.layoutParams as RelativeLayout.LayoutParams
            tvParams.rightMargin = margin as Int
            if (margin > mWidth - textWidth){
                tvParams.leftMargin = (mWidth - textWidth - margin).toInt()
            }
            // 设置文本视图的布局参数
            tv.layoutParams = tvParams
        }
        //设置动画的播放目标
        anim.setTarget(tv)
        //设置动画的播放时长
        anim.duration = 5000
        //设置属性动画的插值器
        anim.interpolator = LinearInterpolator()
        //属性动画开始播放
        anim.start()
        //添加属性动画的监听器
        anim.addListener(object :AnimatorListener{
            override fun onAnimationStart(animation: Animator?) {

            }

            override fun onAnimationEnd(animation: Animator?) {
                layout.removeView(tv)
            }

            override fun onAnimationCancel(animation: Animator?) {

            }

            override fun onAnimationRepeat(animation: Animator?) {

            }
        })
    }

    /**
     * 获取评论内容的文本视图
     */
    private fun getCommentView(content:String):TextView{
        val tv = TextView(context)
        tv.apply {
            text = content
            textSize = mTextSize.toFloat()
            setTextColor(getColorByContent(content))
            isSingleLine = true
            setBackgroundColor(Color.TRANSPARENT)
            val tvParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT)
            // 垂直方向居中
            tvParams.addRule(RelativeLayout.CENTER_VERTICAL)
            //与上级布局右对齐
            tvParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
            //设置文本视图的布局参数
            tv.layoutParams = tvParams
        }
        return tv
    }

    /**
     * 根据昵称获取对应的头像
     * @param content String
     * @return Int
     */
    private fun getColorByContent(content:String): Int {
        val md5:String = MD5Util.encrypt(content)
        val lastChar = md5[md5.lastIndex]
        val pos = if(lastChar >= 'A') lastChar - 'A'+10 else lastChar - '0'
        return COLOR_ARRAY[pos]
    }
}